package logic

import (
	"context"
	"database/sql"
	"fmt"

	"mail/service/account/rpc/account"
	"mail/service/receipt/rpc/internal/svc"
	"mail/service/receipt/rpc/receipt"

	"github.com/dtm-labs/dtmgrpc"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"google.golang.org/grpc/status"
)

type ConceptRevertLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewConceptRevertLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ConceptRevertLogic {
	return &ConceptRevertLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ConceptRevertLogic) ConceptRevert(in *receipt.ConceptRequest) (*receipt.ConceptResponse, error) {
	// todo: add your logic here and delete this line
	db, err := sqlx.NewMysql(l.svcCtx.Config.Mysql.DataSource).RawDB()
	if err != nil {
		return nil, status.Error(500, err.Error())
	}
	//获得子事务屏障对象
	barrier, err := dtmgrpc.BarrierFromGrpc(l.ctx)
	if err != nil {
		return nil, status.Error(500, err.Error())
	}
	//开启子事务屏障
	if err := barrier.CallWithDB(db, func(tx *sql.Tx) error {
		_, err = l.svcCtx.AccountRpc.Particular(l.ctx, &account.ParticularRequest{Id: in.Uid})
		if err != nil {
			return fmt.Errorf("concept exist on account.")
		}
		coincide, err := l.svcCtx.ReceiptModel.Converge(in.Uid, 0, 1)
		if err != nil {
			return fmt.Errorf("receipt isn't exists.")
		}
		//默认取第一个
		sharp := coincide[0]
		//修改状态为9，标记为失效订单、并更新订单
		sharp.Status = 9
		err = l.svcCtx.ReceiptModel.TxUpdate(tx, sharp)
		if err != nil {
			return fmt.Errorf("receipt remeby error.")
		}
		return nil
	}); err != nil {
		return nil, status.Error(500, err.Error())
	}

	return &receipt.ConceptResponse{}, nil
}
